package com.inspur.cloud.controller;

import com.inspur.cloud.dao.dataspace.HdfsResourceDao;
import com.inspur.cloud.entity.dataspace.UserEntity;
import com.inspur.cloud.entity.dataspace.ao.user.LoginAO;
import com.inspur.cloud.entity.dataspace.common.*;
import com.inspur.cloud.entity.dataspace.vo.ShowListBackParam;
import com.inspur.cloud.entity.dataspace.vo.UserDetailsBackParamToHuiZhi;
import com.inspur.cloud.enums.RoleEnum;
import com.inspur.cloud.security.AuthorizationHelper;
import com.inspur.cloud.service.dataspace.LoginService;
import com.inspur.cloud.service.dataspace.RangerRestService;
import com.inspur.cloud.service.dataspace.UserManagerService;
import com.inspur.cloud.service.dataspace.UserUtilService;
import com.inspur.cloud.util.StringUtil;
import com.inspur.cloud.util.TConstants;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang.StringUtils;
import org.mapstruct.Context;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import javax.annotation.security.RolesAllowed;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;

@RestController
@RequestMapping("/dataspace/api/v1/user")
@Api(value = "user",description = "用户操作")
public class UserController {
    @Autowired
    UserManagerService userManagerService;
    @Autowired
    UserUtilService userUtilService;
    @Autowired
    private LoginService loginService;
    @Autowired
    private HdfsResourceDao hdfsResourceDao;
    @Autowired
    private RangerRestService rangerRestService;
    @PostMapping("/login")
    @ApiOperation(value = "用户登录", notes = "对接人：changxw")
    public OpEntityResult<LoginAO> login() {
        OpEntityResult<LoginAO> result = new OpEntityResult<>();
        result.setData(loginService.oper());
        result.setMsg("登录成功");
        result.setCode(1);
        return result;
    }
    @PostMapping("/logout")
    @ApiOperation(value = "登出", notes = "对接人：changxw")
    public OpResult logout(@Context HttpServletRequest httpServletRequest) {
        OpResult result = new OpResult();
        SecurityContextHolder.clearContext();
        httpServletRequest.getSession().invalidate();
        result.setMsg("登出成功");
        result.setCode(1);
        return result;
    }
    @PutMapping("/password")
    @ApiOperation(value = "修改密码", notes = "对接人：changxw")
    public OpResult updatePassword(
            @ApiParam(value = "修改下级密码：id/新密码 ；修改自己密码：旧密码/新密码：")
            @RequestBody UserUpdatePasswordParam param) {
        UserEntity userLogin = AuthorizationHelper.getUser();
        OpResult result = new OpResult();
        result.setCode(-1);
        //修改任何角色都需要新密码 否则不能完成修改工作
        if (StringUtils.isBlank(param.getNewPassword())) {
            result.setMsg("新密码为空，无法完成修改");
            return result;
        }
        userManagerService.updatePassword(param.getOldPassword(), param.getNewPassword(), param.getUserId(), userLogin);
        result.setCode(1);
        result.setMsg("密码修改成功");
        return result;
    }

    @PutMapping("/userController/password")
    @ApiOperation(value = "修改密码   汇智专用", notes = "对接人：changxw")
    public OpResult updatePasswordToHuiZhi(
            @ApiParam(value = "修改下级密码：id/新密码 ；修改自己密码：旧密码/新密码：")
            @RequestBody UserUpdatePasswordParam param) {
        UserEntity userLogin = AuthorizationHelper.getUser();
        OpResult result = new OpResult();
        result.setCode(-1);
        //修改任何角色都需要新密码 否则不能完成修改工作
        if (StringUtils.isBlank(param.getNewPassword())) {
            result.setMsg("新密码为空，无法完成修改");
            return result;
        }
        userManagerService.updatePassword(param.getOldPassword(), param.getNewPassword(), param.getUserId(), userLogin);
        result.setCode(1);
        result.setMsg("密码修改成功");
        return result;
    }
    @PostMapping("/addUser")
    @ApiOperation(value = "添加租户/用户", notes = "对接人：changxw")
    @RolesAllowed({"Admin", "Tenant"})
    public OpEntityResult<Integer> addUserOrTenant(
            @ApiParam(value = "添加租户或者添加用户")
            @RequestBody UserAddParam param) {
        UserEntity userLogin = AuthorizationHelper.getUser();
        OpEntityResult<Integer> result = new OpEntityResult<>();
        result.setCode(-1);
        if(StringUtil.isEmpty(param.getUserName())||StringUtil.isEmpty(param.getPassword())) {
            result.setMsg("输入参数不完整");
            return result;
        }
        param.setUserName(param.getUserName().toLowerCase());
        //判断用户名是否为range中的关键字
        if(rangerRestService.isExistUser(param.getUserName())){
            result.setMsg("range中已存在该用户的权限，无法创建" );
            return  result;
        }
//        String str=param.getUserName().toLowerCase();
//        boolean contains = Arrays.asList(TConstants.specStr).contains(str);
//        if(contains){
//            result.setMsg("用户名为资源类型关键字，无法创建");
//            return  result;
//        }
        //检查资源信息是否存在
        result=userUtilService.isResExist(param.getUserName());
        if (result.getCode()==-1){
            return result;
        }
        //创建kerberos用户
        userManagerService.checkAndAddKerberos(param.getUserName(), param.getPassword());
        //添加数据库信息
        Integer userId = userManagerService.add(param, userLogin);
        result.setMsg("添加成功");
        result.setData(userId);
        result.setCode(1);
        return result;
    }

    @PostMapping("/adduserOrTanent")
    @ApiOperation(value = "添加租户/用户   汇智专用", notes = "对接人：changxw")
    @RolesAllowed({"Admin", "Tenant"})
    public OpEntityResult<Addparam> addUserOrTenant2(
            @ApiParam(value = "添加租户或者添加用户")
            @RequestBody UserAddParamHuizhi param) {
        UserEntity userLogin = AuthorizationHelper.getUser();
        OpEntityResult<Addparam> result = new OpEntityResult<>();
        Addparam addparam = new Addparam();
        result.setCode(-1);
        result.setData(null);
        if(StringUtil.isEmpty(param.getUserName())||StringUtil.isEmpty(param.getPword())) {
            result.setMsg("输入参数不完整");
            return result;
        }
        param.setUserName(param.getUserName().toLowerCase());
        //判断用户名是否为关键字
        if(rangerRestService.isExistUser(param.getUserName())){
            result.setMsg("range中已存在该用户的权限，无法创建" );
            return  result;
        }
        //检查资源信息是否存在
        result=userUtilService.isResExist(param.getUserName());
        if (result.getCode()==-1){
            return result;
        }
        //创建kerberos用户
        userManagerService.checkAndAddKerberos(param.getUserName(), param.getPword());
        //添加数据库信息
        UserAddParam userAddParam = new UserAddParam();
        userAddParam.setDescription(param.getDescription());
        userAddParam.setPassword(param.getPword());
        userAddParam.setUserName(param.getUserName());
        Integer userId = userManagerService.add(userAddParam, userLogin);
        addparam.setUserId(userId);
        result.setData(addparam);
        result.setMsg("添加成功");
        result.setCode(1);
        return result;
    }
    // deleteUser
    @DeleteMapping("/deleteUser")
    @ApiOperation(value = "删除租户/用户", notes = "对接人：changxw")
    public OpResult deleteUser(
            @ApiParam(value = "被删除用户id")
            @RequestParam("userId") Integer userId,
            @ApiParam(value = "是否删除资源，1：删除资源 0：不删除")
            @RequestParam(value = "isDelResource", defaultValue = "0",required =false) Integer isDelResource) {
        UserEntity userLogin=AuthorizationHelper.getUser();
        OpResult result = new OpResult();
        result.setCode(-1);
        result = userManagerService.deleteUser(userId, userLogin, isDelResource);
        return result;
    }
    //去掉userLoginId 和userid
    @GetMapping("/list")
    @ApiOperation(value = "列表显示", notes = "对接人：changxw")
    public PageResult<ShowListBackParam> listUser(@ApiParam(value = "列表查询对象") ListParam param,
                                                  @ApiParam(value = "当前页数")
                                                  @RequestParam(value = "pageIndex", defaultValue = "1") Integer pageIndex,
                                                  @ApiParam(value = "每页条数")
                                                  @RequestParam(value = "pageSize", defaultValue = "10") Integer pageSize) {
        PageResult<ShowListBackParam> pageResult = new PageResult<>();
        pageResult.setCode(-1);
        UserEntity userLogin = AuthorizationHelper.getUser();
        //分页查询需要的id 用于标记是否为租户查询租户
        Integer id = userLogin.getId();
        if (pageIndex < 1 || pageSize > 50) {
            pageResult.setMsg("参数输入不正确");
            return pageResult;
        }
        //租户获取租户 id赋值为管理员的id
        if ("1".equals(param.getIsTenantGetTen()) && userLogin.getRole().equals(RoleEnum.Tenant.getValue())) {
            id = TConstants.ADMIN_ID;
        }
        String userName = param.getUserName();
        if (!StringUtil.isEmpty(userName)) {
            userName = StringUtil.specialStr(userName);
            param.setUserName(userName);
        }
        ShowListParam showListParam = new ShowListParam(pageIndex, pageSize, param.getUserName(), param.getIsTenantGetTen(), userLogin.getName());
        pageResult = userUtilService.showList(showListParam, id);
        pageResult.setMsg("查询成功");
        pageResult.setCode(1);
        return pageResult;
    }
    @GetMapping("/userDetails")
    @ApiOperation(value = "用户详情", notes = "对接人：changxw")
    public OpEntityResult<UserEntity> userDetails(@ApiParam(value = "用户id") @RequestParam("userId") Integer userId) {
        UserEntity loginUser = AuthorizationHelper.getUser();
        OpEntityResult<UserEntity> opEntityResult = new OpEntityResult<>();
        opEntityResult.setCode(-1);
        if (null == userId) {
            opEntityResult.setMsg("输入为空");
            return opEntityResult;
        }
        UserEntity getUser = userManagerService.getUserDetails(loginUser, userId);
        opEntityResult.setCode(1);
        opEntityResult.setData(getUser);
        return opEntityResult;
    }

    @GetMapping("userController/user")
    @ApiOperation(value = "用户详情   汇智专用", notes = "对接人：changxw")
    public OpEntityResult<UserDetailsBackParamToHuiZhi> userDetailsToHuiZhi(@ApiParam(value = "租户/用户id") @RequestParam("userId") Integer userId) {
        UserEntity loginUser = AuthorizationHelper.getUser();
        OpEntityResult<UserDetailsBackParamToHuiZhi> opEntityResult = new OpEntityResult<>();
        opEntityResult.setCode(-1);
        if (null == userId) {
            opEntityResult.setMsg("输入为空");
            return opEntityResult;
        }
        UserEntity getUser = userManagerService.getUserDetails(loginUser, userId);
        UserDetailsBackParamToHuiZhi paramToHuiZhi = new UserDetailsBackParamToHuiZhi(getUser);
        opEntityResult.setCode(1);
        opEntityResult.setData(paramToHuiZhi);
        return opEntityResult;
    }
    @PutMapping("/updateUser")
    @ApiOperation(value = "编辑用户", notes = "对接人：changxiaowei")
    public OpResult edit(@RequestBody EditUserParam editUserParam) {
        UserEntity userLogin = AuthorizationHelper.getUser();
        OpResult opResult = new OpResult();
        userManagerService.updateUserDescription(editUserParam,userLogin);
        opResult.setMsg("编辑成功");
        opResult.setCode(1);
        return opResult;
    }

    // 修改传参为用户id  id驼峰
    @GetMapping("/downloadKeytab")
    @ApiOperation(value = "下载keytab文件", notes = "对接人：changxiaowei")
    public void downLoadKeytab(@ApiParam(value = "用户id id和用户名不能同时为空") @RequestParam(value = "userId", required = false) Integer userId,
                               @Context HttpServletResponse response) {
        userUtilService.downloadZip(userId, response);
    }

    @GetMapping("/userController/keytab")
    @ApiOperation(value = "下载keytab文件  汇智专用", notes = "对接人：changxiaowei")
    public void downLoadKeytabToHuiZhi(@ApiParam(value = "用户id id和用户名不能同时为空") @RequestParam(value = "userId", required = false) Integer userId,
                                       @Context HttpServletResponse response) {
        userUtilService.downloadZip(userId, response);
    }
    //  UnlockParam 中的userName
    @PostMapping("/unlock")
    @ApiOperation(value = "解锁/锁定用户", notes = "对接人：changxiaowei")
    public OpResult unlock(@RequestBody UnlockParam param) {
        UserEntity userLogin = AuthorizationHelper.getUser();
        OpResult result = new OpResult();
        result.setCode(-1);
        if (null == param.getUserId() || StringUtils.isBlank(param.getType()) || !((("1").equals(param.getType().trim())) || ("0".equals(param.getType().trim())))) {
            result.setMsg("参数为空或输入有误");
            return result;
        }
        userUtilService.lockOrUnlock(param, userLogin);
        result.setMsg("成功");
        result.setCode(1);
        return result;
    }

    @GetMapping("/isExist")
    @ApiOperation(value = "查询用户是否存在", notes = "对接人：changxiaowei")
    public OpResult isExist(@ApiParam(value = "用户名") @RequestParam String userName) {
        OpResult opResult = new OpResult();
        opResult.setCode(-1);
        if (null == userName) {
            opResult.setMsg("请输入用户名");
            return opResult;
        }
        if (null != userManagerService.findByName(userName)) {
            opResult.setMsg("该用户已经存在");
            return opResult;
        }
        opResult.setCode(1);
        opResult.setMsg("该用户不存在，可以创建");
        return opResult;
    }
    @GetMapping("/urlIsExist")
    @ApiOperation(value = "查询hdfs路径是否存在", notes = "对接人：changxiaowei")
    public OpResult urlIsExist(@ApiParam(value = "hdfs路径") @RequestParam String url) {
        OpResult result = new OpResult();
        result.setCode(-1);
        if (StringUtils.isBlank(url)) {
            result.setMsg("路径为空");
            return result;
        }
        if (null != hdfsResourceDao.findFirstByUrl(url)) {
            result.setMsg("该路径已经存在");
            return result;
        }
        result.setMsg("该路径不存在，可以创建");
        result.setCode(1);
        return result;
    }
    }


